package org.itboys.mysql.utils;

import java.beans.PropertyDescriptor;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.beanutils.ConvertUtils;
import org.apache.commons.lang.ClassUtils;

/**
 * Bean工具类
 */
public class BeanUtils {

	/** 类的属性和读方法的映射关系缓存 */
	private static final Map<Class<?>, Map<String, Method>> readMethodMappingCache = new HashMap<Class<?>, Map<String, Method>>();
	/** 类的属性和写方法的映射关系缓存 */
	private static final Map<Class<?>, Map<String, Method>> writeMethodMappingCache = new HashMap<Class<?>, Map<String, Method>>();
	
	/**
	 * 获得类的属性和读方法的映射关系
	 * 
	 * @param clazz
	 * @return Map<String, Method> key: 属性名，value： 读方法反射对象
	 */
	public static Map<String, Method> getReadMethodMapping(Class<?> clazz) {
		Map<String, Method> getLowerMapping = readMethodMappingCache.get(clazz);
		if(getLowerMapping != null) {
			return getLowerMapping;
		}
		getLowerMapping = new HashMap<String, Method>();
		Map<String, Method> getUpperMapping = new HashMap<String, Method>();
		Map<String, Method> isLowerMapping = new HashMap<String, Method>();
		Map<String, Method> isUpperMapping = new HashMap<String, Method>();
		for (Method method : clazz.getMethods()) {
			if(Modifier.isStatic(method.getModifiers()) || method.getParameterTypes().length > 0) {
				continue;
			}
			String methodName = method.getName();
			if(method.getReturnType() == boolean.class && methodName.startsWith("is")) {
				if(methodName.matches("^is[a-z_].*$")) {
					isLowerMapping.put(methodName.substring(2), method);
				} else if(methodName.matches("^is[A-Z].*$")) {
					isUpperMapping.put(methodName.substring(2, 3).toLowerCase() + methodName.substring(3), method);
				}
			} else {
				if(methodName.matches("^get[a-z_].*$")) {
					getLowerMapping.put(methodName.substring(3), method);
				} else if(methodName.matches("^get[A-Z].*$")) {
					getUpperMapping.put(methodName.substring(3, 4).toLowerCase() + methodName.substring(4), method);
				}
			}
		}
		for (String field : getUpperMapping.keySet()) {
			getLowerMapping.put(field, getUpperMapping.get(field));
		}
		for (String field : isLowerMapping.keySet()) {
			getLowerMapping.put(field, isLowerMapping.get(field));
		}
		for (String field : isUpperMapping.keySet()) {
			getLowerMapping.put(field, isUpperMapping.get(field));
		}
		readMethodMappingCache.put(clazz, getLowerMapping);
		return getLowerMapping;
	}

	/**
	 * 获得类的属性和写方法的映射关系
	 *
	 * @param clazz
	 * @return
	 */
	public static Map<String, Method> getWriteMethodMapping(Class<?> clazz) {
		Map<String, Method> setLowerMapping = writeMethodMappingCache.get(clazz);
		if(setLowerMapping != null) {
			return setLowerMapping;
		}
		setLowerMapping = new HashMap<String, Method>();
		Map<String, Method> setUpperMapping = new HashMap<String, Method>();
		for (Method method : clazz.getMethods()) {
			if(Modifier.isStatic(method.getModifiers()) || method.getParameterTypes().length != 1) {
				continue;
			}
			String methodName = method.getName();
			if(methodName.matches("^set[a-z_].*$")) {
				setLowerMapping.put(methodName.substring(3), method);
			} else if(methodName.matches("^set[A-Z].*$")) {
				setUpperMapping.put(methodName.substring(3, 4).toLowerCase() + methodName.substring(4), method);
			}
		}
		for (String field : setUpperMapping.keySet()) {
			setLowerMapping.put(field, setUpperMapping.get(field));
		}
		writeMethodMappingCache.put(clazz, setLowerMapping);
		return setLowerMapping;
	}
	
	/**
	 * 将Map转换成beanClass指定的类型对象
	 * @param <T>
	 * @param map
	 * @param beanClass
	 * @return
	 */
	public static <T> T toBean(Map<String, Object> map, Class<T> beanClass) {
		try {
			T bean = beanClass.newInstance();
			Map<String, Method> writeMethodMapping = getWriteMethodMapping(beanClass);
			for (String field : map.keySet()) {
				if(!writeMethodMapping.keySet().contains(field)) {
					continue;
				}
				Method method = writeMethodMapping.get(field);
				Object value = map.get(field);
				Object newVaule = null;
				Class<?> type = method.getParameterTypes()[0];
				if(value == null) {
					newVaule = ObjectUtils.getInitialValue(type);
				} else if(ClassUtils.primitiveToWrapper(type).isInstance(value)) {
					newVaule = value;
				} else {
					newVaule = ConvertUtils.convert(value, type);
				}
				method.invoke(bean, newVaule);
			}
			return bean;
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}
	
	/**
	 * 将bean对象转换成Map
	 * 
	 * @param bean
	 * @return
	 */
	public static Map<String, Object> toMap(Object bean) {
		Map<String, Object> map = new HashMap<String, Object>();
		Map<String, Method> readMethodMapping = getReadMethodMapping(bean.getClass());
		for (String field : readMethodMapping.keySet()) {
			try {
				map.put(field, readMethodMapping.get(field).invoke(bean));
			} catch (Exception e) {
				throw new RuntimeException(e);
			}
		}
		return map;
	}

	/**
	 * 将bean对象按fields指定的属性顺序转换成List
	 * 
	 * @param bean
	 * @param fields
	 * @return
	 */
	public static List<Object> toList(Object bean, String... fields) {
		List<Object> list = new ArrayList<Object>();
		for (String field : fields) {
			try {
				list.add(new PropertyDescriptor(field, bean.getClass()).getReadMethod().invoke(bean));
			} catch (Exception e) {
				throw new RuntimeException(e);
			}
		}
		return list;
	}

}
